package com.gec.hawsteproject.hawaste.controller;

import com.gec.hawsteproject.hawaste.entity.ResponseStatus;
import com.gec.hawsteproject.hawaste.entity.ResultBean;
import com.gec.hawsteproject.hawaste.entity.SysUser;
import com.gec.hawsteproject.hawaste.service.ISysUserService;
import com.gec.hawsteproject.hawaste.utils.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class MainController {
    @Autowired
    ISysUserService userService;
    /**
     * 登录
     * 1.校验传入验证码是否正确
     * 2.匹配账户密码是否正确，正确则跳转到index页，并且讲用户绑定到session
     * 错误显示错误
     */
    @RequestMapping("doLogin")
    @ResponseBody
    public ResultBean   doLogin(@RequestParam Map<String,Object> params, HttpSession session){
    if (params.containsKey("username")&&!ObjectUtils.isEmpty(params.get("username"))&&
            params.containsKey("password")&&!ObjectUtils.isEmpty(params.get("password"))) {
        SysUser sysUser = new SysUser();
        String username = (String) params.get("username");
        sysUser.setUsername(username);
//        密码匹配逻辑：讲用户传入的密码进行加密后与数据库加密的密码进行比较
        String password = (String) params.get("password");
        sysUser.setUsername(password);
        sysUser.setPassword((EncryptUtils.MD5_HEX(EncryptUtils.MD5_HEX(password)+username)));
        sysUser = userService.selectByNameAndPwd(sysUser);
        if (sysUser!=null){
            sysUser.setPassword(null);//不对密码进行状态管理
            //放入session
            session.setAttribute("loginUser",sysUser);
            return ResultBean.ok();
        }
    }
    return ResultBean.fail(ResponseStatus.USERNAME_PASS_ERROR);
    }
    /**
     * 登出
     */
    @RequestMapping("loginout")
    public String loginout(HttpSession session){
        session.invalidate();
        return "redirect:/login.html";
    }
}
